package com.ys.service.business.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.ys.entity.sys.TbStaticConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.finance.TcwAccountDetailedForCompany;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.storage.TccLocation;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.sys.TsOperateOrg;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.finance.FinanceMapper;
import com.ys.mapper.finance.TcwAccountDetailedForCompanyMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.sys.TsOperateOrgService;
import com.ys.util.DateUtil;
import com.ys.util.SnowflakeIdWorker;
import com.ys.vo.R;

@Service("tcwAccountDetailedForCompanyService")
public class TcwAccountDetailedForCompanyServiceImpl implements TcwAccountDetailedForCompanyService {

    private static final Logger logger = LoggerFactory.getLogger(TcwAccountDetailedForCompanyServiceImpl.class);

	@Autowired
	private DiySqlMapper diySqlMapper;
	@Autowired
	private FinanceMapper financeMapper;

	@Autowired
	private TcwAccountDetailedForCompanyMapper tcwAccountDetailedForCompanyMapper;


	@Autowired
	private TsOperateOrgService tsOperateOrgService;

	@Override
	public void updateBatch() {
		diySqlMapper.updateTcwAccountDetailedForCompanyBatch();
	}

	@Override
	public void completeDataByGuid(String guid) {
		diySqlMapper.updateTcwAccountDetailedForCompanyByGuid(guid);
	}



	/**
	 * 新增一条流水
	 * 必填：vGsBm划出公司编码；vGsBmP划入公司编码；vJyLx交易类型；fJe交易金额；dJySj交易时间；dShSj审核时间；vBz备注
	 * 选填：mName;mType;mNid;mBid;mGuid；writeTime记账时间（如果为空，默认审核时间）
	 */
	@Override
	public R addTcwAccountDetailedForCompany(String vgsbm, String vgsbmp, String vjylx, BigDecimal fje,Date djysj, Date dshsj,String vbz,
											 String mbid,Date writeTime) throws Exception{

		//参数验证
		String errorMsg = checkData(vgsbm,vgsbmp,vjylx,fje,djysj,dshsj,vbz);
		if(!"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		//划出公司信息
		Map<String,Object> tcwAccountCountForCompany = new TcwAccountCountForCompany()
				//.addField("C.VYhMc AS vYhMc")
				//.addField("C.VYhZh AS vYhZh")
				.addLeftJoin("THR_OperateCompanyApply C ON A.VGsBm = C.VGsBm")
				.setBDeleted(0)
				.setVGsBm(vgsbm)
				.queryFirstMap();
		if(tcwAccountCountForCompany==null){
			return R.error("未查询到划出公司信息");
		}
		String vGsJc = tcwAccountCountForCompany.get("vGsJc")!=null?tcwAccountCountForCompany.get("vGsJc").toString():"";//公司简称

		//划入公司信息
		Map<String,Object> tcwAccountCountForCompanyByP = new TcwAccountCountForCompany()
				//.addField("C.VYhMc AS vYhMc")
				//.addField("C.VYhZh AS vYhZh")
				.addLeftJoin("THR_OperateCompanyApply C ON A.VGsBm = C.VGsBm")
				.setBDeleted(0)
				.setVGsBm(vgsbmp)
				.queryFirstMap();
		if(tcwAccountCountForCompanyByP==null){
			return R.error("未查询到划入公司信息");
		}
		String vGsJcP = tcwAccountCountForCompanyByP.get("vGsJc")!=null?tcwAccountCountForCompanyByP.get("vGsJc").toString():"";//公司简称


		//获取guid
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		String guid = "GSLS-"+idWorker.nextId();

		//参数传入
		TcwAccountDetailedForCompany entity = new TcwAccountDetailedForCompany();


		entity.setGuid(guid);//guid
		//划出公司
		entity.setVgsbm(vgsbm);//运营公司编码
		entity.setVgsjc(vGsJc);//运营公司简称
		//划入公司
		entity.setVgsbmp(vgsbmp);//运营公司编码
		entity.setVgsjcp(vGsJcP);//运营公司简称
		entity.setVjylx(vjylx);//交易类型
		entity.setFje(fje);//交易金额
		entity.setDjysj(djysj);//交易时间
		entity.setDshsj(dshsj);//审核时间
		entity.setVbz(vbz);//备注
		if(mbid!=null)entity.setMbid(mbid);
		entity.setWriteTime(writeTime!=null?writeTime:dshsj);
		entity.setUpdateTime(dshsj);
		entity.setStatus(1);



		//新增
		int result = tcwAccountDetailedForCompanyMapper.insert(entity);
		if(result>0){
			return R.ok();
		}else {
			return R.error("新增失败");
		}
	}



	/**
	 * 新增一条流水
	 * 必填：vGsBm划出公司编码；vGsBmP划入公司编码；vJyLx交易类型；fJe交易金额；dJySj交易时间；dShSj审核时间；vBz备注
	 * 选填：mName;mType;mNid;mBid;mGuid；writeTime记账时间（如果为空，默认审核时间）
	 */
	@Override
	public R addTcwAccountDetailedForCompanyNoTrigger(String vgsbm, String vgsbmp, String vjylx, BigDecimal fje,Date djysj, Date dshsj,String vbz,
											 String mbid,Date writeTime) throws Exception{

		//参数验证
		String errorMsg = checkData(vgsbm,vgsbmp,vjylx,fje,djysj,dshsj,vbz);
		if(!"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		//划出公司信息
		Map<String,Object> tcwAccountCountForCompany = new TcwAccountCountForCompany()
				//.addField("C.VYhMc AS vYhMc")
				//.addField("C.VYhZh AS vYhZh")
				.addLeftJoin("THR_OperateCompanyApply C ON A.VGsBm = C.VGsBm")
				.setBDeleted(0)
				.setVGsBm(vgsbm)
				.queryFirstMap();
		if(tcwAccountCountForCompany==null){
			return R.error("未查询到划出公司信息");
		}
		String vGsJc = tcwAccountCountForCompany.get("vGsJc")!=null?tcwAccountCountForCompany.get("vGsJc").toString():"";//公司简称

		//划入公司信息
		Map<String,Object> tcwAccountCountForCompanyByP = new TcwAccountCountForCompany()
				//.addField("C.VYhMc AS vYhMc")
				//.addField("C.VYhZh AS vYhZh")
				.addLeftJoin("THR_OperateCompanyApply C ON A.VGsBm = C.VGsBm")
				.setBDeleted(0)
				.setVGsBm(vgsbmp)
				.queryFirstMap();
		if(tcwAccountCountForCompanyByP==null){
			return R.error("未查询到划入公司信息");
		}
		String vGsJcP = tcwAccountCountForCompanyByP.get("vGsJc")!=null?tcwAccountCountForCompanyByP.get("vGsJc").toString():"";//公司简称

		//获取guid
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		String guid = "GSLS-"+idWorker.nextId();

		//参数传入
		TcwAccountDetailedForCompany entity = new TcwAccountDetailedForCompany();


		entity.setGuid(guid);//guid
		//划出公司
		entity.setVgsbm(vgsbm);//运营公司编码
		entity.setVgsjc(vGsJc);//运营公司简称
		//划入公司
		entity.setVgsbmp(vgsbmp);//运营公司编码
		entity.setVgsjcp(vGsJcP);//运营公司简称
		entity.setVjylx(vjylx);//交易类型
		entity.setFje(fje);//交易金额
		entity.setDjysj(djysj);//交易时间
		entity.setDshsj(dshsj);//审核时间
		entity.setVbz(vbz);//备注
		if(mbid!=null)entity.setMbid(mbid);
		entity.setWriteTime(writeTime!=null?writeTime:dshsj);
		entity.setUpdateTime(dshsj);
		entity.setStatus(1);



		//新增
		int result = diySqlMapper.insertTcwAccountDetailedForCompany(entity);
		if(result>0){
			return R.ok();
		}else {
			return R.error("新增失败");
		}
	}


	/**
	 * 新增一条流水
	 * 必填：vGsBm划出公司编码；vGsBmP划入公司编码；vJyLx交易类型；fJe交易金额；dJySj交易时间；dShSj审核时间；vBz备注
	 * 选填：mName;mType;mNid;mBid;mGuid；writeTime记账时间（如果为空，默认审核时间）
	 */
	@Override
	public R addTcwAccountDetailedForCompanyWithJc(String vgsbm,String vgsjc, String vgsbmp, String vgsjcp, String vjylx, BigDecimal fje,Date djysj, Date dshsj,String vbz,
												   String mbid,Date writeTime) throws Exception{
		//获取guid
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		String guid = "GSLS-"+idWorker.nextId();
		//参数传入
		TcwAccountDetailedForCompany entity = new TcwAccountDetailedForCompany();

		entity.setGuid(guid);//guid
		//划出公司
		entity.setVgsbm(vgsbm);//运营公司编码
		entity.setVgsjc(vgsjc);//运营公司简称
		//划入公司
		entity.setVgsbmp(vgsbmp);//运营公司编码
		entity.setVgsjcp(vgsjcp);//运营公司简称
		entity.setVjylx(vjylx);//交易类型
		entity.setFje(fje);//交易金额
		entity.setFjeLeft(financeMapper.getFjeOfTcwAccountCountForCompany(vgsbm)); // 账户余额
		entity.setDjysj(djysj);//交易时间
		entity.setDshsj(dshsj);//审核时间
		entity.setVbz(vbz);//备注
		entity.setWriteTime(writeTime!=null?writeTime:dshsj);
		entity.setUpdateTime(dshsj);
		if(mbid!=null)entity.setMbid(mbid);
		entity.setStatus(1);

		//新增
		int result = tcwAccountDetailedForCompanyMapper.insert(entity);
		if(result>0){
			return R.ok();
		}else {
			return R.error("新增失败");
		}



	}



	/**
	 * 新增一条流水,去除触发器
	 * 必填：vGsBm划出公司编码；vGsBmP划入公司编码；vJyLx交易类型；fJe交易金额；dJySj交易时间；dShSj审核时间；vBz备注
	 * 选填：mName;mType;mNid;mBid;mGuid；writeTime记账时间（如果为空，默认审核时间）
	 */
	@Override
	public R addTcwAccountDetailedForCompanyWithJcNoTrigger(String vgsbm,String vgsjc, String vgsbmp, String vgsjcp, String vjylx, BigDecimal fje,Date djysj, Date dshsj,String vbz,
															String mbid,Date writeTime) throws Exception{
		//获取guid
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		String guid = "GSLS-"+idWorker.nextId();
		//参数传入
		TcwAccountDetailedForCompany entity = new TcwAccountDetailedForCompany();

		entity.setGuid(guid);//guid
		//划出公司
		entity.setVgsbm(vgsbm);//运营公司编码
		entity.setVgsjc(vgsjc);//运营公司简称
		//划入公司
		entity.setVgsbmp(vgsbmp);//运营公司编码
		entity.setVgsjcp(vgsjcp);//运营公司简称
		entity.setVjylx(vjylx);//交易类型
		entity.setFje(fje);//交易金额
		entity.setFjeLeft(financeMapper.getFjeOfTcwAccountCountForCompany(vgsbm)); // 账户余额
		entity.setDjysj(djysj);//交易时间
		entity.setDshsj(dshsj);//审核时间
		entity.setVbz(vbz);//备注
		entity.setWriteTime(writeTime!=null?writeTime:dshsj);
		entity.setUpdateTime(dshsj);
		if(mbid!=null)entity.setMbid(mbid);
		entity.setStatus(1);

		//新增
		int result = diySqlMapper.insertTcwAccountDetailedForCompany(entity);
		if(result>0){
			return R.ok();
		}else {
			return R.error("新增失败");
		}



	}


	//定时新增流水：资金占用费
	@Override
	public void fundOccupyCost() throws Exception{
		List<Map<String,Object>> accountList = new TcwAccountCountForCompany()
				.addLeftJoin("THR_OperateCompanyApply O ON O.Vgsbm = A.Vgsbm")
				.addField("O.OperateOrgId AS operateOrgId")//所属运营机构ID
				.addField("O.OperationsStatus AS operationsStatus")//状态
				.addField("A.vGsBm AS vgsbm")
				.addField("A.vGsJc AS vgsjc")
				.addField("A.fJe AS fje")
				.addField("O.OperationsAttribute AS operationsAttribute")//运营属性
				.where("A.fJe < 0 ")
				.queryMap();

		//获取运营账户 所属的账户属性
		List<TbStaticConfig> operationsAttributeList = new TbStaticConfig()
				.setKeyOne("THR_OperateCompanyApply")
				.setKeyTwo("OperateCompanyApply-OperationsAttribute")
				//.setName("运营账户")
				.where("A.NameSub IN ('运营账户','直营账户')")
				.queryList();

		if(accountList!=null && accountList.size()>0){
			//获取‘运营事业部’底下的运营公司信息
			List<TsOperateOrg> childrenList = tsOperateOrgService.getAllChildrenById(2L);
			String orgInfoIds = "";
			for(TsOperateOrg orgInfo:childrenList){
				orgInfoIds += ","+orgInfo.getId();
			}
			logger.info("‘运营事业部’底下的运营公司信息："+orgInfoIds);

			//筛选信息，只获取‘运营事业部’底下的运营公司
			List<Map<String,Object>> accountListByNew = new ArrayList<>();
			for(Map<String,Object> item:accountList){
				logger.info("获取："+item);
				if(item.get("operateOrgId")!=null){
					boolean isBelong = false;
					for(TsOperateOrg orgInfo:childrenList){
						if(orgInfo.getId().equals(Long.parseLong(item.get("operateOrgId").toString()))
								&& item.get("operationsStatus")!=null
								&& Integer.parseInt(item.get("operationsStatus").toString())==2 //运营状态为正常的才收取资金占用费
						){
							//运营事业部以下，运营账户才扣资源占用费
							for(TbStaticConfig tbStaticConfig:operationsAttributeList){
								if(Integer.parseInt(item.get("operationsAttribute").toString()) == tbStaticConfig.getLev()){
									logger.info("刷取运营公司："+item.get("vgsbm"));
									isBelong = true;
									break;
								}

							}
//							logger.info("刷取运营公司："+item.get("vgsbm"));
//							isBelong = true;
//							break;
						}

					}
					if(isBelong){
						accountListByNew.add(item);
					}
				}
			}

			Date date = new Date();
			String today = DateUtil.getYYYY_MM_DD(date);
			String yesterday = DateUtil.getYYYY_MM_DD(DateUtil.addDays(date,-1));

			for(Map<String,Object> item:accountListByNew){

				if(item.get("fje")!=null && new BigDecimal(item.get("fje").toString()).compareTo(BigDecimal.ZERO)!=0){
					BigDecimal fje = new BigDecimal(item.get("fje").toString()).abs();
					BigDecimal fundOccupyCost = BigDecimal.ZERO;

					if(fje.compareTo(new BigDecimal(10000))<=0){
						fundOccupyCost = new BigDecimal(5);
					}else {
						fundOccupyCost = new BigDecimal(10);
					}
					int hasAdd = new TcwAccountDetailedForCompany().setVgsbm(item.get("vgsbm").toString())
							.setVjylx("运营服务→资源占用费")
							.where("A.DJySj BETWEEN '"+today+" 00:00:00' AND '"+today+" 23:59:59'")
							.count();
					logger.info("hasAdd:"+hasAdd+";新增流水："+item);
					if(hasAdd>0){//已新增过，不再新增
						continue;
					}

					//新增流水
					addTcwAccountDetailedForCompanyWithJcNoTrigger(
							item.get("vgsbm").toString(),item.get("vgsjc").toString(),
							"GS0616", "财务部",
							"运营服务→资源占用费", fundOccupyCost.negate(),date, date,
							yesterday+"，资金不达标资源占用费，账上资金："+ fje.negate(),null,
							date);

					addTcwAccountDetailedForCompanyWithJcNoTrigger(
							"GS0616", "财务部",
							item.get("vgsbm").toString(),item.get("vgsjc").toString(),
							"运营服务→资源占用费", fundOccupyCost,date, date,
							yesterday+"，资金不达标资源占用费，账上资金："+ fje.negate(),null,
							date);
				}
			}
		}
	}


	//定时新增流水：占库费
	@Override
	public void occupyInventoryCost() throws Exception{

		//获取所有仓库信息
		List<Map<String,Object>> locationList = new TccLocation()
				.addLeftJoin("TCC_WarehouseArea B ON B.Ckq = A.Ckq")//库区
				.addLeftJoin("TCC_Warehouse C ON C.Cck = B.Cck")//仓库
				.addField("C.vck AS vck,B.vkq AS vkq")
				.setStatus(1)
				.queryMap();
		//获取所有库存信息
		List<TccStockControl> stockControlList = new TccStockControl()
				.setIsParent(1)//母件
				//.where("A.Chw IS NOT NULL")
				.queryList();

		List<TbStaticConfig> operationsAttributeList = new TbStaticConfig()
				.setKeyOne("THR_OperateCompanyApply")
				.setKeyTwo("OperateCompanyApply-OperationsAttribute")
				//.setName("运营账户")
				.where("A.NameSub IN ('运营账户','直营账户')")
				.queryList();

		//获取所有运营公司信息
		List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().setOperationsStatus(2).queryList();

        Date date = new Date();
		String today = DateUtil.getYYYY_MM_DD(date);
        String yesterday = DateUtil.getYYYY_MM_DD(DateUtil.addDays(date,-1));

		if(companyList!=null && companyList.size()>0
		&& locationList!=null && locationList.size()>0
		&& stockControlList!=null && stockControlList.size()>0){

			for(ThrOperateCompanyApply companyItem:companyList){
				List<TccStockControl> stockControlListByVgsbm = stockControlList.stream()
						.filter(item->item.getVgsbm().equals(companyItem.getVgsbm())
						&& item.getGdepot()!=null && item.getVkq()!=null && item.getVhw()!=null)
						.collect(Collectors.toList());
				if(stockControlListByVgsbm.size()>0){
					BigDecimal fje = BigDecimal.ZERO;
                    BigDecimal productNumAll = BigDecimal.ZERO;
					for(TccStockControl stockItem:stockControlListByVgsbm){
						List<Map<String,Object>> locationByChw = locationList.stream()
								.filter(item->
										item.get("vck")!=null && item.get("vkq")!=null && item.get("vhw")!=null
										&& item.get("vck").toString().equals(stockItem.getGdepot())//仓库名称
										&& item.get("vkq").toString().equals(stockItem.getVkq())//库区名称
										&& item.get("vhw").toString().equals(stockItem.getVhw())//货位名称
								)
								.collect(Collectors.toList());
						if(locationByChw.size()>0){
							TccLocation locationItem = JSON.parseObject(JSON.toJSONString(locationByChw.get(0)), TccLocation.class);
							//TccLocation locationItem = locationByChw.get(0);
							BigDecimal feeStandard = BigDecimal.ZERO;
                            BigDecimal productNum = BigDecimal.ZERO;
							if(locationItem.getFeeStandard()!=null) feeStandard = locationItem.getFeeStandard();
                            if(stockItem.getProductNumAll()!=null) productNum = new BigDecimal(stockItem.getProductNumAll());
							BigDecimal fjeCount = productNum.multiply(feeStandard).setScale(2, BigDecimal.ROUND_HALF_UP);
                            fje = fje.add(fjeCount);
                            productNumAll = productNumAll.add(productNum);
							logger.info("运营公司编码："+companyItem.getVgsbm());
							logger.info("仓库信息："+locationByChw.get(0));
							logger.info("资金："+fje+"；母件库存数量："+productNumAll);
						}
					}
					boolean isBelong = false;
					//运营事业部以下，运营账户才扣资源占用费
					for(TbStaticConfig tbStaticConfig:operationsAttributeList){
						if(companyItem.getOperationsAttribute().equals(tbStaticConfig.getLev())){
							//logger.info("刷取运营公司："+item.get("vgsbm"));
							isBelong = true;
						}

					}
					if(fje.compareTo(BigDecimal.ZERO)>0 && isBelong){

						int hasAdd = new TcwAccountDetailedForCompany().setVgsbm(companyItem.getVgsbm())
								.setVjylx("仓储服务→仓储费")
								.where("A.DJySj BETWEEN '"+today+" 00:00:00' AND '"+today+" 23:59:59'")
								.count();
						logger.info("hasAdd:"+hasAdd+";新增流水："+companyItem.getVgsbm()+";fje="+fje);
						if(hasAdd>0){//已新增过，不再新增
							continue;
						}


                        //新增流水
                        addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                companyItem.getVgsbm(),companyItem.getVgsjc(),
                                "GS0608", "仓储部",
                                "仓储服务→仓储费", fje.negate(),date, date,
                                yesterday+"，仓储费，母件库存数量："+ productNumAll,null,
                                date);

                        addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                "GS0608", "仓储部",
                                companyItem.getVgsbm(),companyItem.getVgsjc(),
                                "仓储服务→仓储费", fje,date, date,
                                yesterday+"，仓储费，母件库存数量："+ productNumAll,null,
                                date);
                    }
				}
			}
		}







	}



	/**
	 * 参数验证
	 * vGsBm划出公司编码；vGsBmP划入公司编码；vJyLx交易类型；fJe交易金额；dJySj交易时间；dShSj审核时间；vBz备注
	 */
	public String checkData(String vgsbm, String vgsbmp, String vjylx, BigDecimal fje,Date djysj, Date dshsj,String vbz){
		Predicate<String> isNotNull = item-> item!=null && !"".equals(item.trim());//是否为空，返回：非空true，空false
		String errorMsg = "";
		if(!isNotNull.test(vgsbm)){
			return "划出公司编码为空！";
		}
		if(!isNotNull.test(vgsbmp)){
			return "划入公司编码为空！";
		}
		if(!isNotNull.test(vjylx)){
			return "交易类型为空！";
		}
		if(fje==null){
			return "交易金额为空！";
		}
		if(djysj==null){
			return "交易时间为空！";
		}
		if(dshsj==null){
			return "审核时间为空！";
		}
		if(!isNotNull.test(vbz)){
			return "备注为空！";
		}
		return errorMsg;
	}

}
